package com.jrauto.CarAppBackend.controller;

/**
 * @author : huiMing
 * Date : 2025年06月27日 16:22
 * @version V1.0
 */

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jrauto.CarAppBackend.entity.dto.CarRequestDTO;
import com.jrauto.CarAppBackend.entity.Car;
import com.jrauto.CarAppBackend.entity.dto.CarQueryDTO;
import com.jrauto.CarAppBackend.entity.vo.CarListVO;
import com.jrauto.CarAppBackend.entity.vo.CarVO;
import com.jrauto.CarAppBackend.entity.vo.MyCarListVO;
import com.jrauto.CarAppBackend.service.CarService;
import com.jrauto.CarAppBackend.utils.R;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 汽车管理 RESTful API 控制器
 */
@Tag(name = "CarController", description = "二手车信息管理")
@RestController
@RequestMapping("/car")
public class CarController {

    @Resource
    private CarService carService;

    /**
     * 分页查询已上架的汽车列表，包含主图
     * GET /cars/list
     *
     * @param pageNum  页码，默认为1
     * @param pageSize 每页记录数，默认为10
     * @return 统一响应结果，包含分页后的汽车列表
     */
    @GetMapping("/list")
    public R<IPage<CarListVO>> listPublishedCars(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        IPage<CarListVO> carPage = carService.listPublishedCarsWithMainImage(pageNum, pageSize);
        return R.ok(carPage);
    }

    /**
     * 汽车详情接口：根据车辆ID查询汽车所有信息和所有相关图片
     * GET /cars/{carId}
     * @param carId 车辆ID
     * @return 统一响应结果，包含汽车详情和媒体列表
     */
    @GetMapping("/{carId}")
    public R<CarVO> getCarDetails(@PathVariable Integer carId) {
        CarVO carVO = carService.getCarDetailsWithMedia(carId);
        if (carVO == null) {
            return R.fail("Car not found or not published.");
        }
        return R.ok(carVO);
    }


    /**
     * 新增车辆信息及关联图片。
     * 前端需先将图片上传至COS，并将COS URL列表随车辆数据一起提交。
     * 请求体示例:
     * {
     * "car": {
     * "brand": "奔驰",
     * "series": "C级",
     * "title": "2020款 奔驰C级 C260L 运动版",
     * "vin": "VIN1234567890",
     * "price": 250000.00,
     * "power": 1,
     * "sellerType": 1,
     * "salesRegion": 1,
     * "manufactureDate": "2020-05-01",
     * "mileage": 30000,
     * "publisherId": 1
     * // ... 其他车辆字段
     * },
     * "imageUrls": [
     * "[https://jrauto-1681731.cos.ap-guangzhou.myqcloud.com/cars/main_car.jpg](https://jrauto-1681731.cos.ap-guangzhou.myqcloud.com/cars/main_car.jpg)",
     * "[https://jrauto-1681731.cos.ap-guangzhou.myqcloud.com/cars/side_car.jpg](https://jrauto-1681731.cos.ap-guangzhou.myqcloud.com/cars/side_car.jpg)"
     * ]
     * }
     * @param request 包含车辆信息和图片URL列表的DTO
     * @return 响应实体
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addCar(@RequestBody CarRequestDTO request) {

        Map<String, Object> response = new HashMap<>();
        try {
            Car car = request.getCar();
            List<String> imageUrls = request.getImageUrls();
//            if (car == null) {
//                response.put("message", "车辆信息不能为空。");
//                return ResponseEntity.badRequest().body(response);
//            }
//            if (car.getVin() == null || car.getVin().isEmpty()) {
//                response.put("message", "车架号（VIN）不能为空。");
//                return ResponseEntity.badRequest().body(response);
//            }

            Car newCar = carService.addCar(car, imageUrls);
            response.put("message", "车辆及图片信息添加成功！");
            response.put("carId", newCar.getCarId());
//            response.put("car", newCar); // 返回完整的车辆信息，包含回填的ID和媒体列表
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (RuntimeException e) {
            response.put("message", "添加车辆失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 更新车辆信息及关联图片。
     * 前端需传递最新的完整图片URL列表（包含旧的和新上传的）。
     * @param carId 车辆ID
     * @param request 包含车辆信息和最新图片URL列表的DTO
     * @return 响应实体
     */
    @PutMapping("/{carId}")
    public ResponseEntity<Map<String, String>> updateCar(@PathVariable Integer carId, @RequestBody CarRequestDTO request) {
        Map<String, String> response = new HashMap<>();
        try {
            Car car = request.getCar();
            List<String> newImageUrls = request.getImageUrls();

            if (car == null || car.getCarId() == null || !car.getCarId().equals(carId)) {
                response.put("message", "请求体中的车辆ID与路径不匹配或车辆信息为空。");
                return ResponseEntity.badRequest().body(response);
            }
            // 确保ID一致
            car.setCarId(carId);

            boolean success = carService.updateCar(car, newImageUrls);
            if (success) {
                response.put("message", "车辆及图片信息更新成功！");
                return ResponseEntity.ok(response);
            } else {
                response.put("message", "更新失败，车辆不存在或数据异常。");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (RuntimeException e) {
            response.put("message", "更新车辆失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 根据ID删除车辆信息及关联的COS图片。
     * @param carId 车辆ID
     * @return 响应实体
     */
    @DeleteMapping("/{carId}")
    public ResponseEntity<Map<String, String>> deleteCar(@PathVariable Integer carId) {
        Map<String, String> response = new HashMap<>();
        try {
            boolean success = carService.deleteCar(carId);
            if (success) {
                response.put("message", "车辆及其关联图片已成功删除！");
                return ResponseEntity.ok(response);
            } else {
                response.put("message", "删除失败，车辆不存在或操作异常。");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (RuntimeException e) {
            response.put("message", "删除车辆失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 汽车下架接口：将汽车状态设置为已下架(status=2)
     * PUT /car/{carId}/offline
     * @param carId 车辆ID
     * @return 统一响应结果
     */
    @PutMapping("/offline/{carId}")
    public R<String> offlineCar(@PathVariable Integer carId) {
        try {
            boolean success = carService.offlineCar(carId);
            if (success) {
                return R.ok("汽车已下架！");
            } else {
                return R.fail("汽车已下架失败！");
            }
        } catch (RuntimeException e) {
            return R.fail("汽车下架异常！");
        }
    }



    /**
     * 汽车下架接口：将汽车状态设置为审核状态(status=0)
     * @param carId 车辆ID
     * @return 统一响应结果
     */
    @PutMapping("/publish/{carId}")
    public R<String> publish(@PathVariable Integer carId) {
        try {
            boolean success = carService.publishCar(carId);
            if (success) {
                return R.ok("汽车已重新发布！");
            } else {
                return R.fail("汽车重新发布失败！");
            }
        } catch (RuntimeException e) {
            return R.fail("汽车重新发布异常！");
        }
    }

    /**
     * 查询自己发布的汽车列表，包含主图
     * GET /cars/my-published/{publisherId}
     * @param userId 发布人ID
     * @return 统一响应结果，包含汽车列表
     */
    @GetMapping("/user/{userId}")
    public R<List<MyCarListVO>> listMyPublishedCars(@PathVariable Integer userId) {
        List<MyCarListVO> carList = carService.listCarsByPublisherId(userId);
        return R.ok(carList);
    }


    // 查询
    /**
     * 单条件查询：根据编号查询
     * GET /cars/search/carNumber
     * @param carNumber 车辆编号
     * @return 统一响应结果，包含汽车列表
     */
    @GetMapping("/search/carNumber")
    public R<List<CarVO>> searchByCarNumber(@RequestParam String carNumber) {
        List<CarVO> carList = carService.listPublishedCarsByCarNumber(carNumber);
        return R.ok(carList);
    }

    /**
     * 单条件查询：根据汽车品牌查询
     * GET /cars/search/brand
     * @param brand 汽车品牌
     * @return 统一响应结果，包含汽车列表
     */
    @GetMapping("/search/brand")
    public R<IPage<CarListVO>> searchByBrand(@RequestParam String brand, @RequestParam(defaultValue = "1") int pageNum,
                                        @RequestParam(defaultValue = "10") int pageSize) {
        IPage<CarListVO> carPage = carService.listPublishedCarsByBrand(brand,pageNum, pageSize);
        return R.ok(carPage);
    }

    /**
     * 单条件查询：根据地区（省市区）查询
     * GET /cars/search/region
     * @param province 省份 (可选)
     * @param city 城市 (可选)
     * @param district 区县 (可选)
     * @return 统一响应结果，包含汽车列表
     */
    @GetMapping("/search/region")
    public R<List<CarVO>> searchByRegion(
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String district) {
        List<CarVO> carList = carService.listPublishedCarsByRegion(province, city, district);
        return R.ok(carList);
    }

    /**
     * 双条件查询：地区（省市区）+标题（模糊查找）
     * GET /cars/search/regionAndTitleFuzzy
     * @param province 省份 (可选)
     * @param city 城市 (可选)
     * @param district 区县 (可选)
     * @param title 标题关键字
     * @return 统一响应结果，包含汽车列表
     */
    @GetMapping("/search/title")
    public R<IPage<CarListVO>> searchByRegionAndTitleFuzzy(
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String district,
            @RequestParam String title,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        IPage<CarListVO> carList =  carService.listPublishedCarsByTitleFuzzy(province, city, district, title,pageNum, pageSize);
        return R.ok(carList);
    }


    /**
     * 多条件查询
     * POST /cars/search/multiCondition
     * @param queryDTO 查询条件DTO
     * @return 统一响应结果，包含汽车列表
     */
    @PostMapping("/search/multiCondition")
    public R<List<CarVO>> searchMultiCondition(@RequestBody CarQueryDTO queryDTO) {
        List<CarVO> carList = carService.listPublishedCarsMultiCondition(queryDTO);
        return R.ok(carList);
    }

}
